package com.lanhai.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;



public class BasicPostHttpHandler2 implements HttpHandler {
	
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        InputStream is = httpExchange.getRequestBody();
        
        String requestData = is2string(is);
        System.out.println("request: " + requestData);       
        is.close();
        
        String queryParams = httpExchange.getRequestURI().getQuery();
        System.out.println(queryParams);
        File file = new File("D:/hplus/agile_board.html");
        InputStream is2 = new FileInputStream(file);
        Headers responseHeaders = httpExchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/html;charset=utf-8");
        OutputStream os = httpExchange.getResponseBody();
//        BufferedReader l_reader = new BufferedReader(new InputStreamReader(is2));
//        String sCurrentLine = "";
//        StringBuffer sb = new StringBuffer();
//        while ((sCurrentLine = l_reader.readLine()) != null) {
//        	sb.append(sCurrentLine);
//        }
//        System.out.println(sb.toString());
//        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, sb.toString().getBytes().length);      
//    	os.write(sb.toString().getBytes());  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        bos.write(is2.read());
        byte[] buf = new byte[512];
        int len = 0;
        while ((len = is2.read(buf)) != -1){
        	bos.write(buf);
        }
        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, bos.toByteArray().length);
        os.write(bos.toByteArray());
    	is2.close();
        os.flush();
        os.close();  
    }
	
    private String is2string(InputStream is) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, "UTF-8");
        
        for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
    
}
